import { defineComponent, watch, shallowReactive, ref } from 'vue'
import * as echarts from 'echarts'
// 声明类型
const PropsType = {
  data: {
    type: Array,
    default: [],
    require: true
  }
} as const

// 定义主体
export default defineComponent({
  props: PropsType,
  setup(props) {
    // 定义 ref
    const chartRef = ref()
    // 配置项
    let options = {}
    const addBlank = (val) =>{
      const ret = []
      for (let _list of val) {
        ret.push(_list)
        ret.push({
          name: '',
          value: 1
        })
      }
      return ret
    }

    const getColor = (val) =>{
      let result = val.reduce((r, a) => r.concat(a, null), []);
      return result
    }

    watch(
      () => props.data,
      (val: any) => {
        //
        options = {
          tooltip: {
            trigger: 'item'
          },
          legend: null,
          // 可动态生成颜色集合
          color: getColor(val.map((item)=>item.color)),
          series: [
            {
              type: 'pie',
              radius: ['60%', '90%'],
              label: {
                show: false
              },
              data: addBlank(val)
            },
          ]
        }
        // 手动触发更新
        if (chartRef.value) {
          // 通过初始化参数打入数据
          chartRef.value.initChart(options)
        }
      },
      {
        immediate: true,
        deep: true
      }
    )

    return () => {
      const height = "80px"
      const width = "80px"

      return <div>
        <echart ref={chartRef} class="mr-auto" options={options} height={height} width={width} />
      </div>
    }
  }
})

